package com.gun0912.tedbottompicker.adapter;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.gun0912.tedbottompicker.TedBottomPicker;
import com.gun0912.tedbottompicker.view.TedSquareFrameLayout;
import com.gun0912.tedbottompicker.view.TedSquareImageView;
import com.huanglejing.mylibrary.R;

import java.io.File;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by TedPark on 2016. 8. 30..
 */
public class ImageGalleryAdapter extends RecyclerView.Adapter<ImageGalleryAdapter.GalleryViewHolder> {


    ArrayList<PickerTile> pickerTiles;
    Context context;
    TedBottomPicker.Builder builder;
    OnItemClickListener onItemClickListener;
    private RequestListener<Uri, GlideDrawable> requestListener;


    public ImageGalleryAdapter(final Context context, final TedBottomPicker.Builder builder) {

        this.context = context;
        this.builder = builder;

        pickerTiles = new ArrayList<PickerTile>();

        if (builder.showCamera) {
            pickerTiles.add(new PickerTile(PickerTile.CAMERA));
        }

        if (builder.showGallery) {
            pickerTiles.add(new PickerTile(PickerTile.GALLERY));
        }

        Observable.just(pickerTiles).map(new Func1<ArrayList<PickerTile>, ArrayList<PickerTile>>() {
            @Override
            public ArrayList<PickerTile> call(ArrayList<PickerTile> pickerTiles) {
                Cursor imageCursor = null;
                try {
                    final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.ImageColumns.ORIENTATION};
                    final String orderBy = MediaStore.Images.Media.DATE_ADDED + " DESC";


                    imageCursor = context.getApplicationContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
                    //imageCursor = sContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);


                    if (imageCursor != null) {

                        int count = 0;
                        while (imageCursor.moveToNext() && count < builder.maxCount) {
                            String imageLocation = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                            File imageFile = new File(imageLocation);
                            pickerTiles.add(new PickerTile(Uri.fromFile(imageFile)));
                            count++;

                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (imageCursor != null && !imageCursor.isClosed()) {
                        imageCursor.close();
                    }
                    return pickerTiles;
                }
            }
        }).subscribe(new Subscriber<ArrayList<PickerTile>>() {
            @Override
            public void onCompleted() {
                //KLog.d();
            }

            @Override
            public void onError(Throwable e) {
                //KLog.d(e);
            }

            @Override
            public void onNext(ArrayList<PickerTile> pickerTiles) {
                //KLog.d(pickerTiles);
            }
        });
    }

    @Override
    public GalleryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.tedbottompicker_grid_item, null);
        final GalleryViewHolder holder = new GalleryViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(final GalleryViewHolder holder, final int position) {
        final PickerTile pickerTile = getItem(position);
        if (builder.isSingle()) {
            holder.deleteOrNot.setVisibility(View.GONE);
        } else {
            if (pickerTile.isCameraTile() || pickerTile.isGalleryTile()) {
                holder.deleteOrNot.setVisibility(View.GONE);
            } else {
                holder.deleteOrNot.setVisibility(View.VISIBLE);
            }
            if (pickerTile.isSelect()) {
                holder.deleteOrNot.setImageResource(R.drawable.picture_selecte);
            } else {
                holder.deleteOrNot.setImageResource(R.drawable.picture_not_select);
            }
        }
//        if (pickerTile.isSelect()) {
//            holder.deleteOrNot.setImageResource(R.drawable.picture_selecte);
//
//        } else {
//            holder.deleteOrNot.setImageResource(R.drawable.picture_not_select);
//        }


        if (pickerTile.isImageTile()) {
            File file = new File(pickerTile.getImageUri().getEncodedPath());
            if (file != null && file.exists()) {
                //KLog.d("onBindViewHolder", position, pickerTile.getImageUri().getPath(),file.length());
            } else {
                //KLog.d("onBindViewHolder : no exits", position, pickerTile.getImageUri().getPath());
            }

        }

        if (pickerTile.isCameraTile()) {
            holder.iv_thumbnail.setBackgroundResource(builder.cameraTileBackgroundResId);
            holder.iv_thumbnail.setImageDrawable(builder.cameraTileDrawable);
        } else if (pickerTile.isGalleryTile()) {
            holder.iv_thumbnail.setBackgroundResource(builder.galleryTileBackgroundResId);
            holder.iv_thumbnail.setImageDrawable(builder.galleryTileDrawable);

        } else {
            final Uri uri = pickerTile.getImageUri();
            if (builder.imageProvider == null) {
                //KLog.d(" RequestListener new ");
                Glide.with(context)
                        .load(uri)
                        .listener(new RequestListener<Uri, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, Uri model, Target<GlideDrawable> target, boolean isFirstResource) {
                                //图片加载失败的从list中移除
                                //KLog.d("onException", model, pickerTile.getImageUri(),position);
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(final GlideDrawable resource, final Uri model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                                // //KLog.d("onResourceReady", model, target, resource, isFromMemoryCache, isFirstResource);
                                return false;
                            }
                        })
                        .thumbnail(0.1f)
                        .dontAnimate()
                        .centerCrop()
                        .placeholder(R.drawable.ic_gallery)
                        .error(R.drawable.load_img_error)
                        .into(holder.iv_thumbnail);
            } else {
                builder.imageProvider.onProvideImage(holder.iv_thumbnail, uri);
            }


        }


        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClickListener.onItemClick(holder.itemView, position);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return pickerTiles.size();
    }

    public PickerTile getItem(int position) {
        return pickerTiles.get(position);
    }

    public void setOnItemClickListener(
            OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }


    public static class PickerTile {
        public static final int IMAGE = 1;
        public static final int CAMERA = 2;
        public static final int GALLERY = 3;
        protected final Uri imageUri;
        protected final
        @TileType
        int tileType;
        public boolean isSelect = false;

        PickerTile(@SpecialTileType int tileType) {
            this(null, tileType);
        }

        PickerTile(@NonNull Uri imageUri) {
            this(imageUri, IMAGE);
        }

        protected PickerTile(@Nullable Uri imageUri, @TileType int tileType) {
            this.imageUri = imageUri;
            this.tileType = tileType;
        }

        @Nullable
        public Uri getImageUri() {
            return imageUri;
        }

        @TileType
        public int getTileType() {
            return tileType;
        }

        public boolean isImageTile() {
            return tileType == IMAGE;
        }

        public boolean isCameraTile() {
            return tileType == CAMERA;
        }

        public boolean isGalleryTile() {
            return tileType == GALLERY;
        }

        public boolean isSelect() {
            return isSelect;
        }

        public void setSelect(boolean select) {
            isSelect = select;
        }

        @Override
        public String toString() {
            if (isImageTile()) {
                return "ImageTile: " + imageUri;
            } else if (isCameraTile()) {
                return "CameraTile";
            } else if (isGalleryTile()) {
                return "PickerTile";
            } else {
                return "Invalid item";
            }
        }

        @IntDef({IMAGE, CAMERA, GALLERY})
        @Retention(RetentionPolicy.SOURCE)
        public @interface TileType {
        }

        @IntDef({CAMERA, GALLERY})
        @Retention(RetentionPolicy.SOURCE)
        public @interface SpecialTileType {
        }
    }

    class GalleryViewHolder extends RecyclerView.ViewHolder {

        TedSquareFrameLayout root;


        TedSquareImageView iv_thumbnail;
        ImageView deleteOrNot;

        public GalleryViewHolder(View view) {
            super(view);
            root = (TedSquareFrameLayout) view.findViewById(R.id.root);
            iv_thumbnail = (TedSquareImageView) view.findViewById(R.id.iv_thumbnail);
            deleteOrNot = (ImageView) view.findViewById(R.id.iv_select_delete);

        }

    }


}
